/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ImageProcessingGUI;

import com.Zhang.Suen.thinning.ThinningService;
import com.azon.face.detection.ImageDetection;
import com.azon.ip.utils.ImageReader;
import com.azon.ip.utils.ImageWriter;
import com.azon.left.hand.*;
import com.isip.edgeDetection.*;
import com.isip.transformation.*;
import com.isip.transformation.difference.DifferenceFunction;
import com.isip.transformation.difference.SimpleDifference;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Mahdan Ahmad F A
 */
public class CobaGUI extends javax.swing.JFrame {

    /**
     * Creates new form CobaGUI
     */
    public CobaGUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Image Processing");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setFocusable(false);
        setName("Image Processing"); // NOI18N
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setText("Input File :");

        jButton2.setText("Choose File");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Original Image");

        jLabel3.setText("Result");

        jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
        jScrollPane1.setDoubleBuffered(true);

        jScrollPane2.setBackground(new java.awt.Color(255, 255, 255));

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Linear Transformation", "NineN Transformation", "LookUpTable Transformation", "edge 0 :  Difference Function", "edge 0 : Simple Difference", "edge 1 : FreiChen", "edge 1 : Kirsch", "edge 1 : Prewitt", "edge 1 : Robert", "edge 1 : Sobel", "edge 2 : FreiChen", "edge 2 : Prewitt", "edge 2 : Robert", "edge 2 : Sobel", "Check object using chain code", "Check number using chain code", "Check number using Zhang Suen", "Face Detector" }));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel4.setText("Algorithm :");

        jButton1.setText("Execute");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel4)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE)
                            .addComponent(jLabel3))
                        .addGap(44, 44, 44))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)
                        .addContainerGap(176, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jButton2)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jButton1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        String[] suffices = ImageIO.getReaderFileSuffixes();
        
        //String  pathname = System.getProperty("user.home") + System.getProperty("file.separator")+ "Pictures";
        //File    path     = new File(pathname);
        
        JFileChooser openFile = new JFileChooser(".\\images");
        
        
        
        FileFilter filter = new FileNameExtensionFilter("Image File", suffices);
        openFile.setFileFilter(filter);
        //openFile.setCurrentDirectory(path);
        
        if (openFile.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            filepath = openFile.getSelectedFile().getAbsolutePath();
            
            ImageIcon   image = new ImageIcon(filepath);
            JLabel      label = new JLabel(image);
            
            jScrollPane2.setViewportView(label);
            jScrollPane2.setVisible(true);
            
        }
        
        
            

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        
        if (filepath.isEmpty()) {
            JLabel label = new JLabel("Original foto belum di input!", (int) CENTER_ALIGNMENT);
            
            jScrollPane1.setViewportView(label);
        } else {
            try {
                String resultpath = counter + ".jpg";
                
                String algorithm = "" + jComboBox1.getSelectedIndex();
                
                int[][] matrix = ImageReader.ReadImageAsGrayScale(filepath);
                
                int[][] new_matrix = null;
                
                Transformation  t;
                EdgeDetection   edge;
                ImageDetection  detect;
                
                WetLeftHand     wet;
                Guesser         guesser;
                MatrixConverter converter;
                
                int[][] matrix_blackandwhite;
                
                String[] chain_codes;
                String[] shapes;
                
                String forLabel = "";
                switch(algorithm) {
                    case "0":
                        t = new LinearTransformation();
                        new_matrix = t.doTransform(matrix) ;
                        
                        break;
                    case "1":
                        t = new NineNTransformation();
                        new_matrix = t.doTransform(matrix) ;

                        break;
                    case "2":
                        t = new LookUpTableMaker();
                        new_matrix = t.doTransform(matrix);
                        
                        break;
                    
                    case "3":
                        t = new DifferenceFunction();
                        new_matrix = t.doTransform(matrix);
                        
                        break;
                    case "4":
                        t = new SimpleDifference();
                        new_matrix = t.doTransform(matrix);
                        
                        break;

                    case "5":
                        edge = new FreiChenEdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case "6":
                        edge = new KirschEdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case "7":
                        edge = new PrewittEdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case "8":
                        edge = new RobertEdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case "9":
                        edge = new SobelEdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case "10":
                        edge = new FreiChen2EdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case "11":
                        edge = new Prewitt2EdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case "12":
                        edge = new Robert2EdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case "13":
                        edge = new Sobel2EdgeDetection();
                        new_matrix = edge.detect(matrix);
                        
                        break;
                    case "14":
                        wet         = new FilledWetLeftHand();
                        guesser     = new ShapeGuesser();
                        converter   = new MatrixConverter();
                        
                        matrix_blackandwhite    = converter.blackAndWhiteConverter(matrix);
                        
                        chain_codes = wet.doWetLeftHand(matrix_blackandwhite);
                        shapes      = new String[chain_codes.length];
                        
                        for (int i = 0; i < shapes.length; i++) {
                            shapes[i] = guesser.doGueess(chain_codes[i]);
                        }
                        
                        forLabel += "<html>Ditemukan " + chain_codes.length + " benda<br>";
                        
                        for(int i = 0; i < chain_codes.length; i++) {
                            forLabel += ("Benda " + (i + 1) + " = " + shapes[i] + "<br>");
                        }
                        
                        forLabel += "</html>";
                        JLabel label = new JLabel(forLabel, (int) CENTER_ALIGNMENT);
                        
                        jScrollPane1.setViewportView(label);                        
                        break;
                    case "15":
                        wet         = new FilledWetLeftHand();
                        guesser     = new NumberGuesser();
                        converter   = new MatrixConverter();
                        
                        matrix_blackandwhite    = converter.blackAndWhiteConverter(matrix);
                        
                        chain_codes = wet.doWetLeftHand(matrix_blackandwhite);
                        shapes      = new String[chain_codes.length];
                        
                        for (int i = 0; i < shapes.length; i++) {
                            shapes[i] = guesser.doGueess(chain_codes[i]);
                        }
                        
                        forLabel += "<html>Ditemukan " + chain_codes.length + " angka<br>";
                        
                        for(int i = 0; i < chain_codes.length; i++) {
                            forLabel += ("Angka " + (i + 1) + " = " + shapes[i] + "<br>");
                        }
                        
                        forLabel += "</html>";
                        
                        break;
                    case "16":
                        wet         = new ThinnedWetLeftHand();
                        guesser     = new thinnedNumberGuesser();
                        converter   = new MatrixConverter();
                        
                        ThinningService thinner     = new ThinningService();
                        
                        matrix_blackandwhite    = converter.blackAndWhiteConverter(matrix);
                        int[][] thinned_matrix  = thinner.doZhangSuenThinning(converter.blackAndWhiteReverser(matrix_blackandwhite));
                        int[][] reversed_matrix = converter.blackAndWhiteReverser(thinned_matrix);
                        new_matrix              = converter.blackAndWhiteReverter(reversed_matrix);
                        
                        break;
                    case "17":
                        detect = new ImageDetection();
                        
                        int[][] matrix_image = ImageReader.ReadImageAsRGB(filepath);
                        
                        int[][] marked_matrix   = detect.doMark(matrix);
                        int[] border            = detect.doDetect(marked_matrix);
                        new_matrix              = detect.drawBox(border, matrix_image);
                        
                        break;
                    default:

                        break;
                        
                }
                
                if ((algorithm.equalsIgnoreCase("14")) || (algorithm.equalsIgnoreCase("15"))) {
                    JLabel label = new JLabel(forLabel, (int) CENTER_ALIGNMENT);
                        
                    jScrollPane1.setViewportView(label);                                                

                } else if (algorithm.equalsIgnoreCase("17")) {
                    BufferedImage new_img = ImageWriter.WriteImageRGB(new_matrix);
                    ImageWriter.WriteImage(new_img, resultpath);

                    ImageIcon   image = new ImageIcon(resultpath);
                    JLabel      label = new JLabel(image);

                    jScrollPane1.setViewportView(label);
                    jScrollPane1.setVisible(true);

                    counter++;
                } else {
                    BufferedImage new_img = ImageWriter.writeImageGrayScale(new_matrix);
                    ImageWriter.WriteImage(new_img, resultpath);

                    ImageIcon   image = new ImageIcon(resultpath);
                    JLabel      label = new JLabel(image);

                    jScrollPane1.setViewportView(label);
                    jScrollPane1.setVisible(true);

                    counter++;
                    if (algorithm.equalsIgnoreCase("16")) {
                        
                    }
                    
                }
                /*
                jScrollPane1.validate();
                jScrollPane1.revalidate();
                jScrollPane1.repaint();
                jScrollPane1.updateUI(); // */
                
                //System.out.println(algorithm);
            } catch (IOException ex) {
                Logger.getLogger(CobaGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        for (int i = 0; i < counter; i++) {
            File file = new File(".\\" + i + ".jpg");
 
            if(file.delete()){
                    System.out.println(file.getName() + " is deleted!");
            }else{
                    System.out.println("Delete operation is failed.");
            }
        }
    }//GEN-LAST:event_formWindowClosing

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CobaGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new CobaGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
    private String  filepath = "";
    private static  int counter = 0;
}
